package ltd.followkba.page;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.view.View;
import androidx.appcompat.widget.SearchView;
import com.kcbsdk.EventHandler;

import java.util.ArrayList;
import java.util.List;

import ltd.advskin.C;
import ltd.advskin.MRAM;
import ltd.advskin.MSKIN;
import ltd.advskin.base.BaseList;
import ltd.advskin.base.BasePage;

import ltd.advskin.base.KcListHolder;
import ltd.advskin.base.KcListListener;
import ltd.advskin.base.KcTypeListener;
import ltd.advskin.task.TaskFree;
import ltd.advskin.view.KcHeaderView;
import ltd.advskin.view.KcListView;
import ltd.followkba.MAPP;
import ltd.followkba.MDBS;
import ltd.followkba.R;
import ltd.followkba.task.App32;
import ltd.followkba.task.App33;
import ltd.followkba.task.App39;
import ltd.followkba.task.BAppUser;
import ltd.followkba.task.BDbsAccount;
import ltd.followkba.task.EditUtils;
import ltd.followkba.task.RunUtils;
import main.MAPI;

import static ltd.advskin.MSKIN.MSTRING;
import static ltd.advskin.MSKIN.MTOAST;
import static main.MAPI.mMyWorks;

public class SearchUserPage extends BaseList {
    private byte gWorksType;
    private SearchView svSearchList;
    private String gsAppName;
    private String gsSearch;
    private String gsResult;
    private boolean isClick;

    private BDbsAccount mBDbsAccount;

    // 所有的页面都接受同样的方式打开LOG
    public static boolean logEnable;
    public void MLOG(String text) {
        if (logEnable) {
            MSTRING(MAPI.GET_LOG_NAME(this) + text);
        }
    }

    @Override
    public void onInitView() {                       // 使用者需要继承，初始化页面控件等显示
        setLayout(R.layout.page_search_user);
        if (mBaseInput != null) {                   // 可能仅仅需要刷新，未必是重新开始的
            gWorksType = mBaseInput.getInput(0);
            mBaseInput = null;                  // 输入参数的使命已经完成，记得及时销毁之
        }
        mKcHeaderView = (KcHeaderView) findViewById(R.id.khvSearch);
        gsAppName =  MAPP.mWorksName[gWorksType];
        mKcHeaderView.setTitle(String.format("查找%s用户", gsAppName), new KcTypeListener() {
            @Override
            public void onMessage(int type) {
                switch (type) {
                    case KcHeaderView.TYPE_CLICK_LEFT:
                        onFinish();
                        break;
                    case KcHeaderView.TYPE_CLICK_RIGHR:
                        setListView(gTabSelect);
                        break;
                }
            }
        });
        initPageListView( 1 );
        svSearchList = (SearchView) findViewById(R.id.svSearchList);
        svSearchList.setQueryHint("查找用户（名字，ID等）");
        String text = getMemoryText();
        svSearchList.setQuery(text, true);
MLOG("getMemoryTextA A "+text);

        svSearchList.setIconified(false);                    // 设置搜索框直接展开显示。左侧有放大镜(在搜索框中) 右侧有叉叉 可以关闭搜索框
//        svSearchList.setIconifiedByDefault(false);       // 设置搜索框直接展开显示。左侧有放大镜(在搜索框外) 右侧无叉叉 有输入内容后有叉叉 不能关闭搜索框
//        svSearchList.onActionViewExpanded();        // 设置搜索框直接展开显示。左侧有无放大镜(在搜索框中) 右侧无叉叉 有输入内容后有叉叉 不能关闭搜索

        svSearchList.setIconifiedByDefault(false);
        svSearchList.setSubmitButtonEnabled(true);
        svSearchList.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextChange(String newText) {      // 用户输入字符时激发该方法
                return false;
            }

            @Override
            public boolean onQueryTextSubmit(String query) {         // 单击搜索按钮时激发该方法
                searchUser(query);
                return false;
            }
        });


        findViewById(R.id.kbtPasteAdd).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {                   // 粘贴
                // 获取系统剪贴板
                ClipboardManager clipboard = (ClipboardManager) MRAM.mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                // 返回数据
                ClipData clipData = clipboard.getPrimaryClip();
                if (clipData != null && clipData.getItemCount() > 0) {
                    // 从数据集中获取（粘贴）第一条文本数据
                    String text = clipData.getItemAt(0).getText().toString();
                    svSearchList.setQuery(text, true);
                }
            }
        });


        if (MAPP.mBDbsAccount.WorksType == gWorksType){
            mBDbsAccount = MAPP.mBDbsAccount;
        }else {
            mBDbsAccount = new BDbsAccount();
            mBDbsAccount.WorksType = gWorksType;
        }
    }
    @Override
    public void onInitData(){                                                                       // onInitView结束，开始加载数据
            if (MAPP.mBDbsAccount.WorksType != gWorksType) {            // 查找其他APP类型的用户
                if (gWorksType < 32) {
                }else if (gWorksType == 33 || gWorksType == 49) {
                    App33.setUser(null);                            // App33需要一个默认的账号
                }
            }

        mMyWorks.setUiEventCallBack(new EventHandler() {
            @Override
            public void onComplete(int methodType, boolean isFail, String message) {
                if (methodType > 0) {
                }else {
                    if (mMyWorks.isEventDataRefresh()){
                        showInfo();
                    }
                }
            }
        });
        showInfo();
    }
    @Override
    public void onPageUpdate(BasePage basePage) {    // 更新显示页面数据，用于刷新显示 basePage返回上面的页面，可以使用getPageResult()获得返回的内容
        onInitData();
    }
    @Override
    public void onFinish() {       // 使用者选择性继承，用户按了后退键，不继承就直接关闭了
        if (isClick){
            setPageResult(isClick);
        }
        setClose();
    }
    private void showInfo() {
        setListView(gTabSelect, (List) MAPP.mSearch);
    }

    private void searchUser(String text) {
        gsSearch = text;
        gsResult = null;
        mKcListView[gTabSelect].setBusy(String.format("正在查找%s......", text));
//        MDBS.setFreeText(MAPP.mBDbsAccount, gWorksType, "Search", text);
        MAPP.mBDbsAccount.SearchUser = text;
        MLOG("searchA "+ text);
        new TaskFree(null, new TaskFree.Listener() {
            @Override
            public void onMessage(boolean isThread, Object object) {
                if (isThread){
                    MDBS.setBDbsAccount(MAPP.mBDbsAccount);
                    MAPP.mSearch = new ArrayList<>();
                    String[] result = null;
                    if (gWorksType == 33 || gWorksType == 49) {
                        MLOG("searchA "+ gsSearch);
                        result = App33.searchUser(gsSearch);
                        if (result == null){
                            gsResult = App33.getApiError();
                        }
                    }else if (gWorksType == 39) {
                        result = App39.searchUser(gsSearch);
                    }else if (gWorksType < 32) {
                        result = App32.searchUser(gsSearch);
                    }
                    if (result != null) {
                        BAppUser bAppUser = null;
                        EditUtils utils = new EditUtils();
                        for (int index = 0; index < result.length; index++) {
                            if (gWorksType == 33 || gWorksType == 49) {
                                bAppUser = App33.getUserInfo(result[index]);
                                if (bAppUser == null){
                                    gsResult = App33.getApiError();
                                }
                            }else if (gWorksType < 32) {
                                bAppUser = App32.getUserInfo(result[index]);
                            }else if (gWorksType == 39) {
                                bAppUser = App39.getUserInfo(result[index]);
                            }
                            if (bAppUser != null) {
                                bAppUser.WorksType = gWorksType;
                                if (MAPP.mSearch != null) {
                                    MAPP.mSearch.add(bAppUser);
                                }
                                if (MRAM.mActivity != null) {
                                    MRAM.mActivity.runOnUiThread(new Runnable() {
                                        public void run() {
                                            showInfo();
                                        }
                                    });
                                }
                                if (gWorksType == 33 || gWorksType == 49) {
                                    App33.downloadHeadFile(bAppUser);
                                }else if (gWorksType < 32) {
                                    App32.downloadHeadFile(bAppUser);
                                }else if (gWorksType == 39) {
                                    bAppUser.HeadFile = String.format("%sH28_%s.jpg", MRAM.gsCachePath, bAppUser.UserIdS);
                                    utils.downloadPhoto(false, 0, 0, bAppUser.HeadUrl, bAppUser.HeadFile);
                                }
                            }
                        }
                    }
                    return;
                }
                if (gsResult != null) {
                    mBDbsAccount.Status = gsResult;
                    RunUtils.saveBDbsAccount(mBDbsAccount);
                    MTOAST(String.format("查找出错：%s", mBDbsAccount.Status, 2000));

                }
                showInfo();
            }
        });
    }
    private String getMemoryText(){
//        String text = MAPP.mBDbsAccount.SearchUser;
//        MLOG("getMemoryTextA 1 "+text);
//        if (text != null){      // 没有记忆
//            return text;
//        }
        int worksType;
        MLOG("getMemoryTextA 2 "+MAPP.mBDbsAccount.SourceText.length);
        if (MAPP.mBDbsAccount.SourceText.length > 3){
            String name = null;
            String type = null;
            for (int index = 3; index < MAPP.mBDbsAccount.SourceText.length; index++){
                if (name == null){
                    name = MAPP.mBDbsAccount.SourceText[index];
                }else if (type == null){
                    type = MAPP.mBDbsAccount.SourceText[index];
                }
                if (name != null && type != null){
                    worksType = MAPI.STRING_DEC32(type);
                    if (worksType == gWorksType){
                        return name;
                    }
                    if (worksType == 33 && gWorksType == 49){
                        return name;
                    }
                    MLOG(String.format("getMemoryTextA D %s %s %s ", index, name, type));
                    name = null;
                    type = null;
                }
            }
        }
        BDbsAccount bDbsAccount = MDBS.getBDbsAccount(gWorksType, MAPP.mBDbsAccount.AccountName);
        if (bDbsAccount != null){
            return bDbsAccount.SearchUser;
        }
        return "";
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // KcListView的全部处理，放在页面的最后位置统一处理 ///////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    private void initListView(int tab, KcListView kcListView) {
        mKcListView[tab] = kcListView;
        mKcListView[tab].initView(null, MAPP.item_user_select, null, new KcListListener() {
            @Override
            public int onMessage(int type, int tab, Object object) {
                return 0;
            }
            @Override
            public int onBindItemHolder(boolean skipImage, int tab, int position, final KcListHolder holder) {
//                MLOG(String.format("searchUserB: %s", position));
                BAppUser bAppUser = (BAppUser)getListView(tab, position);
                if (bAppUser != null){
                    MSKIN.setBitmap(bAppUser.isSelect ? C.select : C.select_not_yet, holder.mView[0]);
                    MSKIN.setBitmap(bAppUser.HeadFile, holder.mView[1]);
                    MSKIN.setText(bAppUser.UserName, holder.mView[2]);
                    String text = String.format("粉%s关%s歌%s %s", bAppUser.FansQty, bAppUser.CareQty, bAppUser.WorksQty, bAppUser.City);
                    MSKIN.setText(text, holder.mView[3]);

                    holder.mView[0].setTag(bAppUser);
                    holder.mView[0].setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            BAppUser bAppUser = (BAppUser) v.getTag();
                            bAppUser.isSelect = !bAppUser.isSelect;
                            setListView(gTabList);
//                            BDbsAccount bDbsAccount = MDBS.getBrotherAccount(gWorksType, MAPP.mBDbsAccount.AccountName);
                            if (bAppUser.isSelect) {
//                                MLOG(String.format("UserInfoA c %s %s", MAPP.mBDbsAccount.CloneAppType, MAPP.mBDbsAccount.CloneUserIdS));
//                                MDBS.setBAppUser(gWorksType, bAppUser);
                                MDBS.setSearchUser(MAPP.mBDbsAccount, gWorksType, bAppUser);
                                MLOG(String.format("gWorksType %02x %02x", gWorksType, bAppUser.WorksType));
                                MTOAST(String.format("已加入 %s", bAppUser.UserName));
                            }else {
                                MDBS.delSearchUser(MAPP.mBDbsAccount, gWorksType, bAppUser);
                                MTOAST(String.format("已删除 %s", bAppUser.UserName));
                            }
                            isClick = true;
                        }
                    });
                    holder.mView[4].setVisibility(View.GONE);
                }
                return 0;
            }
        });
        // (d)列表最后更新日期时间 (n)下次更新日期时间 (c)当前数量 (q)列表最大的数量
        String text = String.format("没有在%s找到用户", gsAppName);
        mKcListView[tab].setStatus(false, false, "", text, null);
        mKcListView[tab].setTabNumber(tab);
    }

    private void initPageListView(int tabQty) {
        mKcListView = new KcListView[tabQty];
        if (tabQty == 1) {
            mKcListView[0] = (KcListView) findViewById(R.id.klvUpload);
            mKcListView[0].setVisibility(View.VISIBLE);
            initListView(0, mKcListView[0]);
            return;
        }
    }
}

